package com.kuang.controller;

import com.kuang.bean.User;
import com.kuang.service.UserService;
import com.kuang.util.ValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class UserController {
    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;


    //跳转到登录页面
    @RequestMapping("/user/toLogin")
    public String tologin()
    {
        return "login";
    }

    //用户登录
    @RequestMapping("/user/loginUser")
    public String login(User user, HttpServletRequest httpRequest) throws Exception{
            httpRequest.setCharacterEncoding("utf-8");
            User userFinded = userService.loginUser(user);
            System.err.println(userFinded);
            String randomCode = (String) httpRequest.getSession().getAttribute("validateCode");
            String code=httpRequest.getParameter("validateCode");
            if (!code.equals(randomCode)){
                httpRequest.setAttribute("msg","验证码错误，请重新登录");
                //进行转发
                return "login";
            }
            if (userFinded==null){
                httpRequest.setAttribute("msg","用户名或者密码错误");
                return "login";
            }else {
                httpRequest.getSession().setAttribute("user",userFinded);
                httpRequest.setAttribute("msg","登陆成功");
                return "main";
            }
    }

    //验证码实现
    @RequestMapping(value = "/user/captcha",method = RequestMethod.GET)
    public void captcha(@RequestParam(value = "time") String time, HttpServletRequest request, HttpServletResponse response)throws IOException {
        ValidateCode code=new ValidateCode(130,35,30,"validateCode");
        code.getCode(request,response);//后台产生验证码

    }
}
